import { ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STChange, STColumn, STComponent, STData } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map, tap } from 'rxjs/operators';
import { NzFormatEmitEvent, NzTreeNodeOptions } from 'ng-zorro-antd/tree';

@Component({
  selector: 'app-organ-post',
  templateUrl: './post.component.html',
})
export class OrganPostComponent implements OnInit {
  form: FormGroup;

  @ViewChild('modalContentUpdate')
  updateTpl: TemplateRef<any>;

  postName: '';
  postCode: '';
  postTypeId: '';
  postDesc: '';

  selectPostTypeDate: any = {
    list: [
      {
        id: '',
        postTypeName: '',
      },
    ],
  };

  q = {
    pi: 1,
    ps: 10,
    no: '',
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false },
  ];
  @ViewChild('st', { static: true })
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'id', type: 'checkbox' },
    { title: '岗位名称', index: 'postName' },
    { title: '岗位简称', index: 'postCode' },
    { title: '岗位分类', index: 'postTypeId' },
    { title: '备注信息', index: 'postDesc' },
    // {
    //   title: '状态',
    //   index: 'status',
    //   render: 'status',
    //   filter: {
    //     menus: this.status,
    //     fn: (filter, record) => record.status === filter.index,
    //   },
    // },
    // {
    //   title: '更新时间',
    //   index: 'updatedAt',
    //   type: 'date',
    // },
    {
      title: '操作',
      buttons: [
        // {
        //   text: '配置',
        //   click: (item) => this.msg.success(`配置${item.no}`),
        // },
        // {
        //   text: '订阅警报',
        //   click: (item) => this.msg.success(`订阅警报${item.no}`),
        // },
        {
          text: '编辑',
          click: (item) => {
            this.msg.success(`编辑${item.id}`);
            this.add(this.updateTpl);
          },
        },
        {
          text: '删除',
          click: (item) => {
            this.msg.success(`删除${item.id}`);
            this.remove(item.id);
            this.msg.success('删除成功');
          },
        },
      ],
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;
  userGender: Array<{ value: string; label: string }> = [
    { value: '0', label: '男' },
    { value: '1', label: '女' },
  ];
  expandKeys = ['0-0'];
  value?: string;
  company = [
    {
      title: 'Node1',
      value: '0-0',
      key: '0-0',
      children: [
        {
          title: 'Child Node1',
          value: '0-0-1',
          key: '0-0-1',
        },
        {
          title: 'Child Node2',
          value: '0-0-2',
          key: '0-0-2',
        },
      ],
    },
    {
      title: 'Node2',
      value: '0-1',
      key: '0-1',
    },
  ];
  post: Array<{ value: string; label: string }> = [
    { value: '0', label: '董事长' },
    { value: '1', label: 'CEO' },
    { value: '2', label: 'CTO' },
  ];
  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private fb: FormBuilder,
  ) {}

  ngOnInit(): void {
    this.form = this.fb.group({
      postName: [null, [Validators.required]],
      postCode: [null, [Validators.required]],
      postTypeId: '',
      postDesc: '',
    });
    this.getData();
  }

  getData(): void {
    this.loading = true;
    this.q.statusList = this.status.filter((w) => w.checked).map((item) => item.index);
    if (this.q.status !== null && this.q.status > -1) {
      this.q.statusList.push(this.q.status);
    }
    this.http
      .get('api/sysPost/selectByQuery', this.q)
      // .pipe(
      //   map((list: Array<{ status: number; statusText: string; statusType: string }>) =>
      //     list.map((i) => {
      //       const statusItem = this.status[i.status];
      //       i.statusText = statusItem.text;
      //       i.statusType = statusItem.type;
      //       return i;
      //     }),
      //   ),
      //   tap(() => (this.loading = false)),
      // )
      .subscribe((res) => {
        if (res.code === 200) {
          this.msg.success('操作成功');
          this.data = res.data;
        }
        // this.data = res;
        // this.cdr.detectChanges();
      });
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.callNo, 0);
        this.cdr.detectChanges();
        break;
      case 'filter':
        this.getData();
        break;
    }
  }

  remove(postId: string): void {
    this.http.post('api/sysPost/removeById', { id: postId }).subscribe(() => {
      this.getData();
      this.st.clearCheck();
    });
  }

  approval(): void {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  add(tpl: TemplateRef<{}>): void {
    this.modalSrv.create({
      nzTitle: '新建岗位',
      nzContent: tpl,
      nzWidth: 900,

      nzOnOk: () => {
        const params = {
          postName: this.postName,
          postCode: this.postCode,
          postTypeId: this.postTypeId,
          postDesc: this.postDesc,
        };
        alert(params);

        this.http.post('api/sysPost/insert', params).subscribe((res) => {
          if (res.code === 200) {
            this.msg.success('操作成功');
            this.getData();
          }
        });
      },
    });
  }

  reset(): void {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }
  onExpandChange(e: NzFormatEmitEvent): void {
    const node = e.node;
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadNode().then((data) => {
        node.addChildren(data);
      });
    }
  }

  loadNode(): Promise<NzTreeNodeOptions[]> {
    return new Promise((resolve) => {
      setTimeout(
        () =>
          resolve([
            { title: 'Child Node', key: `${new Date().getTime()}-0` },
            { title: 'Child Node', key: `${new Date().getTime()}-1` },
          ]),
        1000,
      );
    });
  }

  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
  }
  _submitForm(): void {}

  selectPostType(): void {
    this.http.post('api/sysPostType/getEnableSysPostTypeList').subscribe((res) => {
      if (res.code === 200) {
        this.msg.success('操作成功');
        this.selectPostTypeDate.list = res.data;
      }
    });
  }
}
